"use client";
import { ServiceTypes } from "@/api/customservice";
import { getPaysApi, lredPacketApi, PayDataType, redPacketApi } from "@/api/promo";
import UserRecharge, { ModalRefProps, Timeout } from "@/components/ModalPopup/RechargeModal";
import RedPacketModal, { RedPacketModalProps } from "@/components/ModalPopup/RedPacketModal";
import SlotsModal, { SlotModalRefProps } from "@/components/ModalPopup/SlotsModal";
import WheelModal, { WheelModalProps } from "@/components/ModalPopup/WheelModal";

import { getWheelApi } from "@/api/cashWheel";
import { getShareApi } from "@/api/config";
import { getGiveInfoApi } from "@/api/slots";
import { Link } from "@/i18n/routing";
import { useGlobalNoticeStore } from "@/stores/useGlobalNoticeStore";
import useWheelStore from "@/stores/useWheelStore";
import { getToken } from "@/utils/Cookies";
import { useRequest } from "ahooks";
import { Badge } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useSearchParams } from "next/navigation";
import { FC, useEffect, useRef } from "react";

interface Props {
    services: ServiceTypes[];
}
/**
 * 免费送活动
 */
const SlotSection = () => {
    const slotsRef = useRef<SlotModalRefProps | null>(null);
    const getSlots = async () => {
        const token = getToken();
        if (token) {
            const result = await getGiveInfoApi();
            return result.data;
        } else {
            return Promise.resolve({});
        }
    };

    const { data: slots, run: slotRun } = useRequest<any, any>(getSlots, {
        pollingInterval: 2000,
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });
    const slotHandler = () => {
        slotsRef.current?.onOpen(slots);
    };
    return (
        <>
            {slots?.id ? (
                <img
                    src={"/slots/slots-icon.gif"}
                    className={"mb-[0.2778rem] w-[100%]"}
                    onClick={slotHandler}
                />
            ) : null}

            {/*随机送*/}
            <SlotsModal ref={slotsRef} onAfterHandler={slotRun} />
        </>
    );
};

/**
 * 轮盘
 */
const WheelSection = () => {
    const wheelModalRef = useRef<WheelModalProps | null>(null);
    const { wheelStatus, wheelCurrent, setWheel } = useWheelStore((state) => ({
        wheelStatus: state.status,
        wheelCurrent: state.currentWheel,
        setWheel: state.setWheel,
    }));

    useEffect(() => {
        setWheel().then((data) => {
            if (data && useWheelStore.getState().status === 1) {
                wheelModalRef.current?.onOpen(data);
            }
        });
    }, []);

    return (
        <>
            {wheelStatus === 2 ? (
                <Link
                    href={"/cashWheel"}
                    className={
                        "mb-[0.2778rem] flex h-[0.54rem] w-[0.54rem] items-center" +
                        " justify-center rounded-[50%] bg-gradient-to-b from-[#0575e6] to-[#00f260]"
                    }
                >
                    <Image src={"/wheels/wheel-icon.gif"} alt={"wheel"} width={100} height={100} />
                </Link>
            ) : null}

            {/*  轮盘弹窗 */}
            <WheelModal ref={wheelModalRef} />
        </>
    );
};
/**
 * 首充
 */
const PaySection = () => {
    const token = getToken();

    const userRechargeRef = useRef<ModalRefProps>(null);
    // 首充活动
    const getPayInfo = async (): Promise<PayDataType> => {
        if (token) {
            const result = await getPaysApi();
            return result.data;
        } else {
            return Promise.resolve({
                first_pay: [],
                pay: [],
            });
        }
    };

    const { data: paysInfo, run: payRun } = useRequest<PayDataType, any>(getPayInfo, {
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });
    return (
        <>
            {paysInfo &&
                paysInfo.first_pay &&
                paysInfo.first_pay.map((item, index) => {
                    return (
                        <div
                            key={index}
                            className={`mb-[0.2778rem] flex cursor-pointer flex-col items-center`}
                        >
                            <img
                                className={"w-[0.54rem]"}
                                src="/hby/recharge.png"
                                onClick={() => {
                                    userRechargeRef.current?.onOpen &&
                                        userRechargeRef.current?.onOpen(paysInfo?.first_pay, index);
                                }}
                            />
                            {item.end_time > 0 ? (
                                <Timeout
                                    className={
                                        "relative before:left-0 before:top-0 before:content-['']" +
                                        " -m-[0.0417rem] before:h-[100%] before:blur-[0.0486rem]" +
                                        " before:absolute before:-z-10 before:w-[100%] before:bg-[#ed9d00]" +
                                        " text-[0.08rem]" +
                                        " z-1 text-[#fff]"
                                    }
                                    endTime={item.end_time}
                                    onEndHandler={payRun}
                                />
                            ) : null}
                        </div>
                    );
                })}

            {/*首充弹窗*/}
            <UserRecharge ref={userRechargeRef} />
        </>
    );
};

/**
 * 红包雨
 */
const RedPacketSection = () => {
    const token = getToken();
    const redPacketModalRef = useRef<RedPacketModalProps>(null);
    const getRedPacketInfo = async () => {
        try {
            let redPacketInfo: any;
            let actList: any = [];
            if (token) {
                redPacketInfo = await lredPacketApi();
                actList = redPacketInfo.data?.red_packets || [];
            } else {
                redPacketInfo = await redPacketApi();
                actList = redPacketInfo.data || [];
            }

            // 已经开始
            return actList.filter((aItem: any) => {
                return aItem.is_start;
            });
        } catch (error) {}
    };
    // 红包雨轮询
    const { data: packets, run } = useRequest<any[], any>(getRedPacketInfo, {
        pollingInterval: 5000,
        pollingErrorRetryCount: 1,
        pollingWhenHidden: false,
    });
    return (
        <>
            {packets?.map((item, index) => {
                const icons = JSON.parse(item.icon);
                const icon = icons[icons.length - 1];
                return (
                    <div key={index} className={`mb-[0.2778rem] cursor-pointer`}>
                        <img
                            className={"w-[0.54rem] object-fill"}
                            src={icon}
                            onClick={() => {
                                redPacketModalRef.current?.onOpen(packets, index);
                            }}
                        />
                    </div>
                );
            })}

            {/*红包雨弹窗*/}
            <RedPacketModal ref={redPacketModalRef} onAfterHandler={run} />
        </>
    );
};

const MessageSection = () => {
    const { unread, userUnred } = useGlobalNoticeStore((state) => ({
        unread: state.unread,
        userUnred: state.userUnred,
    }));
    return (
        <>
            {unread || userUnred ? (
                <Link
                    href={"/notification"}
                    className={
                        "mb-[0.2778rem] flex h-[0.54rem] w-[0.54rem] items-center" +
                        " justify-center rounded-[50%] bg-gradient-to-t from-[#ffa111]" +
                        " to-[#ffcf35]"
                    }
                >
                    <Badge content={userUnred + unread} style={{ "--top": "12px" }}>
                        <i className={"iconfont icon-duanxinguanli text-[0.3rem] text-[#fff]"}></i>
                    </Badge>
                </Link>
            ) : null}
        </>
    );
};
/**
 * 客服
 */
const CustomerSection: FC<Omit<Props, "socials">> = (props) => {
    const { services } = props;
    const defaultService = services?.filter((item) => item.is_suspend === 1);
    return (
        <>
            {defaultService?.map((item, index) => (
                <Link
                    key={index}
                    href={item.url}
                    className={
                        "flex h-[0.54rem] w-[0.54rem] items-center justify-center rounded-[50%]" +
                        " bg-gradient-to-t from-[#ff611b] to-[#ffcf35]"
                    }
                    target={"_blank"}
                >
                    <img
                        className={"h-[0.3889rem] w-[0.3889rem] object-contain"}
                        src={item.icon_url}
                        alt={""}
                    ></img>
                </Link>
            ))}
        </>
    );
};
const ServiceWidget: FC<Props> = (props) => {
    const { services } = props;

    const newServices = services?.filter((item) => item.status === 1) || [];

    const getWheel = () => {
        if (!getToken()) return Promise.resolve(undefined);
        return getWheelApi().then((res) => {
            return res.data;
        });
    };

    const serach = useSearchParams();

    useEffect(() => {
        // 数据存储，侧边栏使用
        // setSocials(socials);

        // 分享地址
        if (serach.get("ch")) {
            getShareApi({ channel_url: window.location.href });
        }
    }, []);

    const t = useTranslations("HomePage");

    return (
        <>
            <div
                className={`absolute bottom-[0.84rem] right-[0.12rem] z-50 flex w-[0.6944rem] flex-col items-center justify-center`}
            >
                <SlotSection />
                {/*轮盘  */}
                <WheelSection />
                {/*首充*/}
                <PaySection />
                {/* 红包雨icon */}
                <RedPacketSection />
                {/*未读消息*/}
                <MessageSection />
                {/*客服*/}
                <CustomerSection services={services} />
            </div>

            <div
                className={`grid`}
                style={{
                    gridTemplateColumns: ` repeat(${newServices && newServices.length >= 5 ? 5 : (newServices?.length ?? 1)},1fr)`,
                }}
            >
                {newServices.map((service, index) => {
                    return (
                        <Link
                            key={index}
                            href={service.url}
                            target={"_blank"}
                            className="bg-white m-[0.05rem] h-[0.3889rem] w-[0.3889rem] rounded"
                        >
                            <img
                                className={"h-[0.3889rem] w-[0.3889rem]"}
                                src={service.icon_url}
                            ></img>
                        </Link>
                    );
                })}
            </div>

            <div className={"text-[#ff6a01]"}>{t("Service")}</div>

            {/*share*/}
            <div className={"my-[0.2rem] text-[0.12rem] text-[#adadad]"}>{t("Share")}</div>

            <Image
                src={"/logo.png"}
                alt={"BCWIN777"}
                width={120}
                height={180}
                className={"mb-[0.2rem]"}
            />
        </>
    );
};

export default ServiceWidget;
